<template>
  <el-container>
    <el-header :style="{'minWidth': width + 'px'}">
      <div class="header">
        <el-row>
          <el-col :span="4">
            <el-icon>
              <Reading />
            </el-icon>
            <i>StudyingPlatform</i>
          </el-col>
          <el-col :span="5">
            <el-menu
              class="style"
              :default-active="activePath"
              mode="horizontal"
              active-text-color="#409EFF"
              @select="selectPath"
            >
              <el-menu-item index="home"> 首页</el-menu-item>
              <el-menu-item index="community">社区</el-menu-item>
              <el-menu-item index="game">学习</el-menu-item>
            </el-menu>
          </el-col>
          <el-col :span="15" class="info">
            <el-menu
              mode="horizontal"
              text-color="#303133"
              style="height: 61px"
            >
              <el-menu-item
                ><el-input
                  @keyup.enter="searchPost"
                  placeholder="请输入内容"
                  v-model="searchMessage"
                  size="large"
                  :suffix-icon="Search"
                >
                  <i
                    @click="searchPost"
                    slot="suffix"
                    class="el-input__icon el-icon-search"
                  ></i>
                </el-input>
                <el-card
                  class="hint"
                  :class="isHide ? 'isHide' : ''"
                  :style="{'width': (width / 24 * 15 * 0.39) + 'px'}"
                >
                  <li
                    v-for="p in messages"
                    :key="p.postId + '123'"
                    @click="searchPostDetail(p.postId)"
                  >
                    {{ p.title }}
                  </li>
                </el-card>
              </el-menu-item>
              <el-sub-menu class="auth" index="1">
                <template #title>
                  <el-avatar
                    size="medium"
                    icon="el-icon-user-solid"
                    :src="profilePhoto"
                  ></el-avatar>
                  <span>{{ authName }}</span>
                </template>
                <div
                  @click="selectPath(item.path)"
                  v-for="item in userMessage"
                  :key="item.id"
                  style="width: 50%; display: inline-block;height: 70px; border-bottom: 1px solid #e8e8ed; cursor: pointer;user-select: none;background-color: #fff;"
                >
                  <span
                    style="display: block;font-size: 18px; text-align: center; font-weight: 700; padding: 10px 0 5px;"
                    >{{
                      item.title }}</span
                  >
                  <span
                    style="display: block;font-size: 18px; text-align: center; font-weight: 700; padding: 5px 0 10px;"
                    >{{
                      item.value
                    }}</span
                  >
                </div>
                <el-menu-item @click="toCreation">
                  <i
                    class="iconfont icon-xuexi"
                    style="font-size: 18px; margin: 0 8.5px 0 3px; color: #909399"
                  ></i>
                  <span slot="title">我要创作</span>
                </el-menu-item>
                <el-menu-item @click="toContentManage">
                  <el-icon style="color: #909399">
                    <Management />
                  </el-icon>
                  <span slot="title">内容管理</span>
                </el-menu-item>
                <el-menu-item @click="toPersonalCenter">
                  <el-icon style="color: #909399">
                    <UserFilled />
                  </el-icon>
                  <span slot="title">个人中心</span>
                </el-menu-item>
                <span
                  style="
                    display: block;
                    height: 1px;
                    border-top: 1px solid #e8e8ed;
                    background-color: #fff;
                  "
                ></span>
                <el-menu-item @click="quit"
                  ><i
                    class="iconfont icon-tuichu"
                    style="font-size: 16px; margin: 0 8px 0 6px; color: #909399"
                  ></i>
                  <span slot="title">退出</span></el-menu-item
                >
              </el-sub-menu>
              <!-- <el-menu-item
                v-show="!showTiming"
                class="message"
                @click="
                            {
                showTiming = true;
                proxy.$storage.setItem('showTiming', showTiming);
              }
                "
              >
                <div class="message-box">
                  <p>{{ hours }}</p>
                  <p>:</p>
                  <p>{{ minutes }}</p>
                  <p>:</p>
                  <p>{{ seconds }}</p>
                </div>
              </el-menu-item> -->
              <el-menu-item
                style="font-family: '华文隶书';font-size: 32px;pointer-events: none"
                >学无止境</el-menu-item
              >
              <el-button
                style="float: right; margin: 10px 10px 10px 15px"
                @click="toManager"
                v-if="userInfo.userRoleId !== 3"
                type="primary"
                size="large"
                >到管理端</el-button
              >
            </el-menu>
          </el-col>
        </el-row>
      </div>
    </el-header>
    <el-main style="min-width: 1200px">
      <router-view :key="$route.fullPath" @getFollows="getFollows" />
      <el-card v-show="showTiming" class="timing">
        <span
          >学习模式<el-icon
            class="el-icon-close"
            @click="
                 {
          showTiming = false;
          proxy.$storage.setItem('showTiming', showTiming);
        }
          "
          >
            <Close /> </el-icon
        ></span>
        <el-input
          :disabled="disabledStudyContentInput"
          type="textarea"
          v-model="studyContent"
          placeholder="请输入今日学习内容"
        ></el-input>
        <div class="time">
          <el-progress
            type="circle"
            :percentage="percentage"
            :show-text="false"
            :stroke-width="10"
            :width="170"
          ></el-progress>
          <el-button
            @click="startToStudy"
            :type="isStart ? 'danger' : 'primary'"
            >{{ !isStart ? '开始' : '结束'
            }}</el-button
          >
          <el-button
            v-show="isStart"
            @click="stopStudy"
            :type="isContinue ? 'warning' : 'success'"
            >{{
            isContinue ? '停止' : '继续' }}</el-button
          >
        </div>
        <div class="text-box">
          <p>{{ hours }}</p>
          <p>:</p>
          <p>{{ minutes }}</p>
          <p>:</p>
          <p>{{ seconds }}</p>
        </div>
      </el-card>
    </el-main>
    <!-- <el-footer style="min-width: 1200px; height: 62px">
      <div>
        <a href="https://beian.mit.gov.cn" style="color: #303133"
          >粤ICP备2023037441号-1</a
        >
      </div>
      <div>copyright © 2023 codingclock.top all rights reserved</div>
    </el-footer> -->
  </el-container>
</template>

<script setup lang="ts">
import { useStore } from 'vuex';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Reading, Search, Management, UserFilled, Close } from '@element-plus/icons-vue'
import { inject, ref, getCurrentInstance, ComponentInternalInstance, reactive, onMounted, watch, computed } from 'vue';
import { dataFormatTime } from '@/utils/data';
import { Base64 } from 'js-base64';
import store from '@/store';
import { useRouter } from 'vue-router';
const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const proxy = appContext.config.globalProperties;
const storeData = useStore();
const router = useRouter();

const reload: any = inject('reload');
// 当前活跃的路由
const activePath = ref(proxy.$storage.getItem('activePath') || 'home')
// 搜索框输入的内容
const searchMessage = ref('');
// 是否隐藏文本提示
const isHide = ref(true);
// 消息数
// const messageNum = ref(12);
// 头像
const profilePhoto = ref('https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png');
// 个人信息
const userMessage = reactive([
  { id: '1', value: 0, title: '粉丝', path: 'personalCenter/myFans' },
  {
    id: '2',
    value: 0,
    title: '关注',
    path: 'personalCenter/myFollowers',
  },
]);
// 账号信息
const userInfo = ref(proxy.$storage.getItem('userInfo') || '')
// 信息
//定义复杂数据类型
interface ArrListType {
  postId: Number
  title: String
}
const messages = ref<ArrListType[]>([]);
// 是否显示学习时间
const showTiming = ref(proxy.$storage.getItem('showTiming') || false)
// 学习内容
const studyContent = ref(proxy.$storage.getItem('studyContent') || '')
// 是否禁用学习内容文本框
const disabledStudyContentInput = ref(false);
// 记录时分秒
const hour = ref(0);
const minute = ref(0);
const second = ref(0);
// 是否开始学习
const isStart = ref(false);
// 是否继续学习
const isContinue = ref(true);
// 进度条进度
const percentage = ref(proxy.$storage.getItem('percentage') || 0);
// 定时器
let timer: Number;
// 开始学习时间和结束学习时间
// const startTime = ref(0);
// const endTime = ref(0);

// 获取浏览器屏幕宽度
const width = ref(0);
onMounted(()=>{
  width.value = window.outerWidth
  // if(width.value <= 1200){
  //   width.value = 1200;
  // }
})

onMounted(() => {
  activePath.value = proxy.$storage.getItem('activePath');
  if (proxy.$storage.getItem('studyTimes')) {
    disabledStudyContentInput.value = true;
    studyContent.value = proxy.$storage.getItem('studyContent') || '';
    if (proxy.$storage.getItem('continueStudy')) {
      isContinue.value = true;
      isStart.value = true;
    } else {
      isContinue.value = false;
      isStart.value = true;
      console.log('proxy===>', proxy);

      proxy.$nextTick(() => {
        window.clearInterval(Number(timer));
        timer = 0;
      });
    }
  }
  if (proxy.$storage.getItem('time')) {
    proxy.hour = proxy.$storage.getItem('time').hour;
    proxy.minute = proxy.$storage.getItem('time').minute;
    proxy.second = proxy.$storage.getItem('time').second;
  }
  getFans();
  getFollows();
  store.dispatch('userSign/getSignInfo', { data: userInfo?.value.userId })
  store.dispatch('userSign/getRank');
});

// 监听当前路由
watch(() => router.currentRoute.value,
  (newValue: any) => {
    proxy.$storage.setItem(
      'activePath',
      proxy.$route.path.substring(1, newValue.path.length)
    );
    activePath.value = proxy.$storage.getItem('activePath');
  },
  { immediate: true }
);
// 搜索框输入的内容
watch(searchMessage, (val: any) => {
  isHide.value = val ? false : true;
  if (!val) return;
  proxy.$request.discussPost
    .search({ pageNum: 1, pageSize: 20 }, { keywords: val })
    .then((res: any) => {
      messages.value = [];
      if (!res.data) return;
      res.data.list.forEach((item: any) => {
        messages.value.push({
          postId: item.postId,
          title: item.title,
        });
      });
    });
})
// 是否开始学习计时
watch(isStart, () => {
  if (isStart.value) {
    proxy.$storage.setItem('continueStudy', true);
    var time = proxy.$storage.getItem('studyTimes') || 0;
    proxy.$storage.setItem('studyContent', studyContent.value);
    timer = window.setInterval(() => {
      if (percentage.value >= 100) {
        percentage.value = 0;
        proxy.$request.exception.refresh().then((res: any) => {
          ElMessage({
            type: 'success',
            message: res.msg,
            duration: 1000,
          });
        });
      }
      percentage.value += 100 / 3600;
      proxy.$storage.setItem('percentage', percentage.value);
      second.value++;
      if (second.value === 60) {
        minute.value++;
        if (minute.value === 60) {
          hour.value++;
          if (hour.value === 24) {
            hour.value = 0;
          }
          minute.value = 0;
        }
        second.value = 0;
      }
      time += 1000;
      proxy.$storage.setItem('studyTimes', time);
      proxy.$storage.setItem('time', {
        hour: hour.value,
        minute: minute.value,
        second: second.value,
      });
    }, 1000);
    disabledStudyContentInput.value = true;
  } else {
    window.clearInterval(Number(timer));
    timer = 0;
    postNewRecord(proxy.$storage.getItem('studyTimes'));
  }
});

// 用户名
const authName = computed(() => {
  return storeData.state.userInf.userInfo.userName
})

// 学习时长的时分秒
const hours = computed(() => {
  return hour.value < 10 ? '0' + hour.value : hour.value;
});
const minutes = computed(() => {
  return minute.value < 10 ? '0' + minute.value : minute.value;
});
const seconds = computed(() => {
  return second.value < 10 ? '0' + second.value : second.value;
})

// 跳转到对应的路由
function selectPath(index: any) {
  proxy.$router.push(`/${index}`);
}
// 点击按钮后退出
function quit() {
  ElMessageBox.confirm('此操作将退出登录, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      proxy.$request.account.logout().then(() => {
        if (isStart.value) {
          return ElMessage({
            type: 'warning',
            message: '请先结束学习记录',
            duration: 1000,
          });
        }
        // 清除token
        proxy.$storage.clearAll();
        window.clearInterval(Number(timer));
        timer = 0;
        // 跳转到登录页面
        proxy.$router.replace('/login');
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消操作',
        duration: 1000,
      });
    });
}
// 搜索帖子
function searchPost() {
  isHide.value = true;
  proxy.$storage.setItem('searchKeywords', searchMessage.value);
  proxy.$storage.setItem('activeIndex', null);
  searchMessage.value = '';
  if (proxy.activePath === 'community') {
    window.clearInterval(Number(timer));
    timer = 0;
    reload();
  } else {
    proxy.$router.push({
      path: '/community',
    });
  }
}
// 搜索帖子详情
function searchPostDetail(postId: any) {
  isHide.value = true;
  searchMessage.value = '';
  const p = Base64.encodeURI(postId);
  proxy.$router.push({
    path: `/communityDetail`,
    query: { p },
  });
}
// 获取粉丝数
function getFans() {
  proxy.$request.follow
    .myfans({
      userId: proxy.$storage.getItem('userInfo').userId,
      pageNum: 1,
      pageSize: 1,
    })
    .then((res: any) => {
      userMessage[0].value = res.data ? res.data.total : 0;
    });
};
// 获取关注数
function getFollows() {
  proxy.$request.follow
    .myfollows({
      userId: proxy.$storage.getItem('userInfo').userId,
      pageNum: 1,
      pageSize: 1,
    })
    .then((res: any) => {
      userMessage[1].value = res.data ? res.data.total : 0;
    });
};
// 是否开始学习
function startToStudy() {
  if (!studyContent.value) {
    return ElMessage({
      type: 'warning',
      message: '请先输入学习内容',
      duration: 1000,
    });
  }
  if (isStart.value) {
    ElMessageBox.confirm(
      `此操作将结束 <strong>${studyContent.value}</strong> 的学习, 是否继续?`,
      '提示',
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
      .then(() => {
        isStart.value = !isStart.value;
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
          duration: 1000,
        });
      });
  } else {
    ElMessageBox.confirm('此操作将确定今日学习内容, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        proxy.$storage.setItem('studyContent', proxy.studyContent);
        isStart.value = !isStart.value;
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消操作',
          duration: 1000,
        });
      });
  }
};
// 停止学习
function stopStudy() {
  if (isContinue.value) {
    isContinue.value = false;
    proxy.$storage.setItem('continueStudy', isContinue.value);
    window.clearInterval(Number(timer));
    timer = 0;
  } else {
    isContinue.value = true;
    proxy.$storage.setItem('continueStudy', isContinue.value);
    var time = proxy.$storage.getItem('studyTimes') || 0;
    proxy.$storage.setItem('studyContent', studyContent.value);
    timer = window.setInterval(() => {
      if (percentage.value >= 100) {
        percentage.value = 0;
      }
      percentage.value += 100 / 3600;
      proxy.$storage.setItem('percentage', percentage.value);
      second.value++;
      if (second.value === 60) {
        minute.value++;
        if (minute.value === 60) {
          hour.value++;
          if (hour.value === 24) {
            hour.value = 0;
          }
          minute.value = 0;
        }
        second.value = 0;
      }
      time += 1000;
      proxy.$storage.setItem('studyTimes', time);
      proxy.$storage.setItem('time', {
        hour: hour.value,
        minute: minute.value,
        second: second.value,
      });
    }, 1000);
    disabledStudyContentInput.value = true;
  }
};
// 学习时间记录
function postNewRecord(studyTime: any) {
  proxy.$request.dailyRecord
    .newRecord({
      createTime: dataFormatTime(),
      studyContent: studyContent.value,
      studyTime: Math.floor(studyTime / 1000),
      userId: proxy.$storage.getItem('userInfo').userId,
    })
    .then((res: any) => {
      ElMessage({
        type: 'success',
        message: res.msg,
        duration: 1000,
      });
      window.clearInterval(Number(timer));
      timer = 0;
      percentage.value = 0;
      disabledStudyContentInput.value = false;
      proxy.$storage.setItem('time', null);
      proxy.$storage.setItem('studyTimes', null);
      proxy.$storage.setItem('percentage', null);
      proxy.$storage.setItem('studyContent', null);
      hour.value = 0;
      minute.value = 0;
      second.value = 0;
      isContinue.value = true;
    });
};
// 点击跳转到我要创作
function toCreation() {
  proxy.$router.push('/creation');
};
// 点击跳转到内容管理
function toContentManage() {
  // 用户id加密
  const i = Base64.encodeURI(userInfo.value.userId);
  // 用户名加密
  const n = Base64.encodeURI(userInfo.value.userName);
  proxy.$router.push({
    path: '/contentManage',
    query: { i, n },
  });
};
// 点击跳转到个人中心
function toPersonalCenter() {
  proxy.$router.push('/personalCenter');
};
// 跳转到管理端
function toManager() {
  if (proxy.$storage.getItem('studyContent')) {
    return ElMessage({
      type: 'warning',
      message: '请先结束学习模式',
      duration: 1000,
    });
  }
  proxy.$router.push('/manager');
};
</script>

<style lang="less" scoped>
.el-container {
  height: 100%;
  width: 100vw;

  .el-header {
    height: 62px !important;
    padding: 0;

    .header {
      height: 60.67px;
      width: 100%;
      box-shadow: 0 1px 2px rgb(0 0 0 / 30%);

      .el-menu-item {
        font-weight: 400;
        font-size: 16px;
      }
      .el-col:nth-child(1) {
        .el-icon {
          float: left;
          height: 60px;
          line-height: 72px;
          left: 5px;
        }

        i {
          font-family: '华文隶书';
          margin-left: 5px;
          font-size: 25px;
          display: inline-block;
          height: 60px;
          line-height: 60px;
        }
      }

      .style {
        margin-left: 20px;

        .el-menu-item {
          background-color: unset;
          height: 60.67px;
          padding: 0 10px;
          margin: 0 10px;
        }
        .el-menu-item:hover {
          background-color: unset;
        }
      }

      .info {
        .el-menu-item:hover {
          background-color: unset;
        }

        .auth {
          /deep/ .el-icon-user-solid:before {
            margin-left: 4px;
            color: #fff;
          }

          span {
            margin-left: 10px;
            font-size: 16px;
          }
        }

        .el-menu-item:nth-child(1) {
          margin: 0 5px;
          width: 39%;

          .hint {
            position: fixed;
            top: 55px;
            z-index: 999999;
            overflow: auto;
            max-height: 240px;
            // width: 19%;

            li {
              padding: 0 8px;
              height: 40px;
              line-height: 40px;
              overflow-x: hidden;
              text-overflow: ellipsis;
              text-align: left;

              &:hover {
                background-color: #eee;
              }
            }
          }

          .isHide {
            display: none;
          }

          /deep/ .el-card__body {
            padding: 0;
          }
        }

        .message {
          .message-box {
            width: 130px;

            p {
              margin: 0;
              display: inline-block;
              font-size: 30px;
              font-weight: 700;
            }
          }
        }
      }
    }
  }

  .el-main {
    background-color: #eaedf1;
    padding: 20px;

    .timing {
      position: absolute;
      z-index: 999;
      right: 28px;
      bottom: 20px;
      min-height: 100px;

      span {
        font-size: 16px;
        font-weight: 600;
        display: block;
        margin-bottom: 10px;

        i {
          float: right;

          &:hover {
            color: #409eff;
          }
        }
      }

      .el-textarea {
        margin-top: 10px;
        width: 253px;
      }

      .time {
        width: 253px;
        text-align: center;

        .el-progress {
          margin: 10px 0;
        }

        .el-button--primary,
        .el-button--danger,
        .el-button--warning,
        .el-button--success {
          width: 100px !important;
        }
      }

      .text-box {
        position: absolute;
        height: 100px;
        line-height: 100px;
        width: 160px;
        margin: -176px 0 0 46px;
        text-align: center;

        p {
          display: inline-block;
          height: 40px;
          line-height: 40px;
          font-size: 30px;
          font-weight: 700;
        }

        p:nth-child(2) {
          margin: 0 3px;
        }
      }
    }
  }

  .el-footer {
    box-shadow: 0 10px 10px rgba(0, 0, 0, 1);
    border-top: 1px solid #ccc;

    div {
      height: 30px;
      line-height: 30px;
      text-align: center;
    }

    div:nth-child(2) {
      line-height: 20px;
    }
  }
}

.el-menu--horizontal .el-menu--horizontal .el-menu .el-menu-item {
  padding: 0 15px;
  color: #555666 !important;
}

.el-menu--horizontal .el-menu .el-menu-item:nth-child(n + 2):hover {
  color: #303133 !important;
  background-color: #f0f0f5;
}

.el-menu--horizontal .el-menu .el-menu-item:nth-child(1) {
  margin: 10px 0 5px 0;
  padding: 0;
  height: 60px;
  border-bottom: 1px solid #e8e8ed;

  .el-statistic {
    /deep/ .title {
      color: #999aaa;
    }

    /deep/ .number {
      font-weight: 600;
    }
  }
}
</style>
